package com.woniu.controller;

import com.woniu.entity.AllGroup;
import com.woniu.entity.AllUser;
import com.woniu.entity.RelUesrGroup;
import com.woniu.entity.dto.BindUsersToGroupRequest;
import com.woniu.mapper.AllUserMapper;
import com.woniu.service.AllGroupService;
import com.woniu.service.AllUserService;
import com.woniu.service.RelUesrGroupService;
import com.woniu.util.ResponseData;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName GroupController
 * @Description 用户分组 以及组分配考试
 * @Author nanqiao
 * @Date 2025/6/13 14:32
 * @Version 1.0
 */
@RestController
@RequestMapping("/group")
public class GroupController {
    @Autowired
    private AllGroupService allGroupService;
    @Autowired
    private RelUesrGroupService relUesrGroupService;
    @Autowired
    private AllUserService userService;

//    查询所有分组
    @GetMapping("/group")
    public ResponseData<List<AllGroup>> list() {
        List<AllGroup> list = allGroupService.list();
        return ResponseData.ok(list);
    }
    /**
     * 新增分组
     */
    @PostMapping
    public ResponseData<String> createGroup(@RequestBody AllGroup group) {
        boolean success = allGroupService.save(group);
        if (success) {
            return ResponseData.ok("分组创建成功");
        } else {
            return ResponseData.fail(400, "分组创建失败");
        }
    }

    /**
     * 绑定多个用户到一个组（已存在则更新 groupId）
     */
    @PostMapping("/bind-users")
    public ResponseData<String> bindUsersToGroup(@RequestBody BindUsersToGroupRequest request) {
        if (request.getGroupId() == null || request.getUserIds() == null || request.getUserIds().isEmpty()) {
            return ResponseData.fail(400, "参数不完整");
        }

        Integer targetGroupId = request.getGroupId();
        List<Integer> userIds = request.getUserIds();

        // 1. 查询数据库中已有的记录
        List<RelUesrGroup> existingRecords = relUesrGroupService.getRelUesrGroupsByUserIds(userIds);

        // 2. 构建需要插入或更新的数据
        List<RelUesrGroup> toSaveList = new ArrayList<>();

        for (Integer userId : userIds) {
            RelUesrGroup record = existingRecords.stream()
                    .filter(r -> r.getUserId().equals(userId))
                    .findFirst()
                    .orElse(null);

            if (record != null) {
                // 已存在，更新 group_id
                record.setGroupId(targetGroupId);
                toSaveList.add(record);
            } else {
                // 不存在，新增记录
                RelUesrGroup newRecord = new RelUesrGroup();
                newRecord.setUserId(userId);
                newRecord.setGroupId(targetGroupId);
                toSaveList.add(newRecord);
            }
        }

        // 3. 批量保存或更新
        relUesrGroupService.saveOrUpdateBatch(toSaveList);

        return ResponseData.ok("用户绑定成功");
    }

    /**
     * 修改分组
     * @param group
     */
    @PutMapping
    public ResponseData<String> updateGroup(@RequestBody AllGroup group) {
        boolean success = allGroupService.updateById(group);
        if (success) {
            return ResponseData.ok("分组更新成功");
        } else {
            return ResponseData.fail(400, "分组不存在或更新失败");
        }
    }

    /**
     * 删除分组（即使 rel_uesr_group 中没有该 group_id 也允许删除）
     */
    @DeleteMapping("/{groupId}")
    public ResponseData<String> deleteGroup(@PathVariable Integer groupId) {
        // 1. 先尝试删除关联用户关系数据（即使不存在也不会影响主表删除）
        try {
            boolean deleted = relUesrGroupService.removeByMap(Map.of("group_id", groupId));
            // 如果删除失败（比如记录不存在），继续执行删除分组操作
        } catch (Exception e) {
            // 可选：记录日志，忽略异常或处理
        }

        // 2. 再删除分组本身
        boolean success = allGroupService.removeById(groupId);
        if (success) {
            return ResponseData.ok("分组删除成功（无关联用户或已清理）");
        } else {
            return ResponseData.fail(400, "分组不存在或删除失败");
        }
    }


    /**
     * 查询所有分组以及分组下的用户
     *
     */
    @GetMapping
    public ResponseData<List<Map<String, Object>>> getAllGroupsWithUsers() {
        // 1. 获取所有分组
        List<AllGroup> groups = allGroupService.list();

        if (groups.isEmpty()) {
            return ResponseData.ok(Collections.emptyList());
        }

        // 2. 获取所有分组ID
        List<Integer> groupIds = groups.stream().map(AllGroup::getGroupId).toList();

        // 3. 查询所有关联记录
        List<RelUesrGroup> relations = relUesrGroupService.getRelUesrGroupsByGroupIds(groupIds);

        // 4. 按 group_id 分组，便于后续查询
        Map<Integer, List<RelUesrGroup>> relationMap = relations.stream()
                .collect(Collectors.groupingBy(RelUesrGroup::getGroupId));

        // 5. 提取所有用户ID
        List<Integer> userIds = relations.stream().map(RelUesrGroup::getUserId).distinct().toList();

        // 6. 查询所有用户详细信息
        List<AllUser> users = userService.listByIds(userIds);

        // 7. 构建返回数据
        List<Map<String, Object>> result = new ArrayList<>();

        for (AllGroup group : groups) {
            Map<String, Object> groupWithUsers = new HashMap<>();
            groupWithUsers.put("group", group);

            List<RelUesrGroup> groupRelations = relationMap.getOrDefault(group.getGroupId(), Collections.emptyList());

            List<Integer> userIdsInGroup = groupRelations.stream().map(RelUesrGroup::getUserId).toList();

            List<AllUser> usersInGroup = users.stream()
                    .filter(user -> userIdsInGroup.contains(user.getUserId()))
                    .toList();

            groupWithUsers.put("users", usersInGroup);
            result.add(groupWithUsers);
        }

        return ResponseData.ok(result);
    }


    /**
     * 根据 ID 查询单个分组以及分组下的用户
     * @param groupId
     */
    @GetMapping("/{groupId}")
    public ResponseData<AllGroup> getGroupById(@PathVariable Integer groupId) {
//        获取分组信息
        AllGroup group = allGroupService.getById(groupId);
        if (group == null){
            return ResponseData.fail(400, "分组不存在");
        }
//        获取分组下的用户信息
        List<RelUesrGroup> relations = relUesrGroupService.getRelUesrGroupsByGroupId(groupId);

        if (relations.isEmpty()) {
            Map<String, Object> result = new HashMap<>();
            result.put("group", group);
            result.put("users", Collections.emptyList());
            return ResponseData.ok(result);
        }

        // 3. 获取每个用户的详细信息（可替换为调用 UserService）
        List<Integer> userIds = relations.stream().map(RelUesrGroup::getUserId).toList();
        // 假设你有 UserService 提供根据 ID 列表查询用户的方法
        List<AllUser> users = userService.listByIds(userIds); // 需要注入并实现

        // 4. 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("group", group);
        result.put("users", users);

        return ResponseData.ok(result);
    }

    /**
     * 根据组id查询组内用户
     */
    @GetMapping("/users/{groupId}")
    public ResponseData<List<AllUser>> getUsersByGroupId(@PathVariable Integer groupId) {
        List<RelUesrGroup> relations = relUesrGroupService.getRelUesrGroupsByGroupId(groupId);
        if (relations.isEmpty()) {
            return ResponseData.ok(Collections.emptyList());
        }
        List<Integer> userIds = relations.stream().map(RelUesrGroup::getUserId).toList();
        List<AllUser> users = userService.listByIds(userIds);
        return ResponseData.ok(users);
    }


}
